const { db, query } = require("../database/db")

// 新增权限
const createpermission = (name, father, sign, type, router_url, component_url, icon, sort) => {
    let sql = `INSERT INTO permission 
        (name,father,sign,type,router_url,component_url,icon,sort)
            VALUES 
        (?,?,?,?,?,?,?,?)`
    return query(sql, [name, father, sign, type, router_url, component_url, icon, sort])
}
// 添加子项权限
const add_son_permis = (name, father, sign, type, router_url, component_url, icon, sort) => {
    let sql = `
        INSERT INTO permission 
        (name,father,sign,type,router_url,component_url,icon,sort)
            VALUES 
        (?,?,?,?,?,?,?,?)
    `
    return query(sql, [name, father, sign, type, router_url, component_url, icon, sort])
}
// 删除权限-软删除
const del_permis_f = (id) => {
    let sql = `UPDATE permission SET state = 1 WHERE id = ?`
    return query(sql, [id])
}
// 删除权限-软删除
const start_state = (id) => {
    let sql = `UPDATE permission SET state = 0 WHERE id = ?`
    return query(sql, [id])
}
// 权限删除-真删除
const del_permis_t = (id) => {
    let sql = `DELETE FROM permission WHERE id = ?`
    return query(sql, [id])
}
// 权限修改--获取数据
const permis_get = (id) => {
    let sql = `SELECT * FROM permission WHERE id = ? AND state = 0`
    return query(sql, [id])
}
// 权限修改--设置数据
const permis_set = (name, father, sign, type, router_url, component_url, icon, sort, id) => {
    let sql = `UPDATE permission SET 
    name=?,father=?,sign=?,type=?,router_url=?,component_url=?,icon=?,sort=?
    WHERE id = ?
    `
    // name,father,sign,type,router_url,component_url,icon,sort,id
    return query(sql, [name, father, sign, type, router_url, component_url, icon, sort, id])
}
function buildPermissionTree(permissions) {
    // 1. 创建节点映射表（id -> node）
    const nodeMap = new Map();
    permissions.forEach(permission => {
        nodeMap.set(permission.id, {
            ...permission,
            key: permission.id,  // 添加key字段
            children: []         // 初始化children数组
        });
    });

    // 2. 构建树形结构
    const tree = [];
    const handledIds = new Set(); // 记录已处理的节点，防止重复

    permissions.forEach(permission => {
        const currentNode = nodeMap.get(permission.id);

        // 如果已经处理过则跳过
        if (handledIds.has(permission.id)) next();

        handledIds.add(permission.id);

        // 如果是顶级节点（father为0或等于自身id）
        if (permission.father === 0 || permission.father === permission.id) {
            tree.push(currentNode);
        } else {
            // 查找父节点
            const parentNode = nodeMap.get(permission.father);

            if (parentNode) {
                // 检查循环引用
                if (!isCircular(parentNode, permission.id)) {
                    parentNode.children.push(currentNode);
                } else {
                    console.warn(`检测到循环引用：权限 ${permission.id} -> ${permission.father}`);
                    // 将循环引用的节点作为顶级节点处理
                    tree.push(currentNode);
                }
            } else {
                // 父节点不存在，作为顶级节点
                tree.push(currentNode);
            }
        }
    });

    return tree;
}
// 检查循环引用的辅助函数
function isCircular(node, targetId) {
    const stack = [...node.children];
    while (stack.length) {
        const currentNode = stack.pop();
        if (currentNode.id === targetId) return true;
        stack.push(...currentNode.children);
    }
    return false;
}
// 列表搜索--分页
const permis_list = async (name, sign, page, page_size) => {
    // 1. 首先获取符合条件的所有数据（不分页）
    let listSql = `SELECT id, father, name, sign, type, router_url, component_url, state FROM permission`;
    let countSql = `SELECT COUNT(*) as count FROM permission`;

    let conditions = [`0 = 0`];
    let params = [];
    let countParams = [];

    if (name) {
        conditions.push(`name LIKE ?`);
        params.push(`%${name}%`);
        countParams.push(`%${name}%`);
    }
    if (sign) {
        conditions.push(`sign LIKE ?`);
        params.push(`%${sign}%`);
        countParams.push(`%${sign}%`);
    }

    const whereClause = conditions.length > 0 ? ` WHERE ${conditions.join(' AND ')}` : '';
    listSql += whereClause;
    countSql += whereClause;

    // 2. 获取总数（所有符合条件的记录）
    const countResult = await query(countSql, countParams);
    const total = countResult[0].count;

    // 3. 获取当前页的扁平数据
    listSql += ` ORDER BY father ASC,id DESC`
    listSql += ` LIMIT ? OFFSET ?`;
    params.push(page_size);
    params.push((page - 1) * page_size);
    const permissionsResult = await query(listSql, params);

    // 4. 转换为树形结构（基于当前页数据）
    const treeData = buildPermissionTree(permissionsResult);

    return {
        permissions: treeData,
        total: total // 返回符合条件的总记录数
    };
};
// 全部权限--接口
const permis_all = async () => {
    let listSql = `SELECT id,father, name FROM permission`;
    return query(listSql)
}
// 全部父级--接口
const permis_all_father = async () => {
    let listSql = `SELECT father FROM permission GROUP BY father`;
    // 执行查询
    const results = await query(listSql);
    // 处理结果，提取 father 属性并创建新数组
    const fathers = results.map(item => item.father);
    return fathers;
}
// 获取用户对应的所以权限
const getUserPermissions = async (id) => {
    let sql = 
    `
        SELECT roles.id, roles.name, permission.name as name, permission.sign as permission_code
        FROM roles 
        LEFT JOIN permission ON FIND_IN_SET(permission.id, roles.permission_ids) > 0
        LEFT JOIN users ON users.role_id = roles.id
        WHERE users.id = ?
    `
    return query(sql,[id])
}

// 获取角色对应的所以权限
const  getRolePermissions = async ( role_id) => {
    let sql = `
        SELECT permission.name as name, permission.sign as permission_code,permission.id as permiss_id
        FROM roles 
        LEFT JOIN permission ON FIND_IN_SET(permission.id, roles.permission_ids) > 0
        LEFT JOIN users ON users.role_id = roles.id
        WHERE roles.id = ?
    `
    return query(sql,[role_id])
}
module.exports = {
    createpermission,
    del_permis_f,
    start_state,
    del_permis_t,
    permis_get,
    permis_set,
    add_son_permis,
    permis_list,
    permis_all,
    permis_all_father,
    getUserPermissions,
    getRolePermissions
}